/*
 * Copyright (C) GSX Techedu Inc. All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

package com.nime.novel.crawl.core.detail;

import com.nime.novel.crawl.constant.StatusEnum;
import com.nime.novel.crawl.domain.CrawlUrl;
import com.nime.novel.crawl.mapper.CrawlBookMapper;
import com.nime.novel.crawl.service.CrawlUrlService;
import com.nime.novel.crawl.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liujialiang
 * @description
 * @team wuhan operational dev.
 * @date 2020/8/28 11:57 下午
 **/
@Slf4j
public abstract class DetailGetService<T> {

    @Autowired
    protected CrawlUrlService crawlUrlService;

    @Autowired
    protected CrawlBookMapper crawlBookMapper;

    protected abstract CrawlUrl getNewestUrl(Integer policyId);

    protected abstract T parseHtml(CrawlUrl crawlUrl, String html);

    protected abstract boolean insert(T entity);

    protected boolean parseDetail(CrawlUrl crawlUrl) {
        String htmlText = HttpUtil.getByHttpClient(crawlUrl.getUrl());
        if (StringUtils.isEmpty(htmlText)) {
            return false;
        }
        // 解析
        T entity = parseHtml(crawlUrl, htmlText);
        if (null == entity) {
            return false;
        }
        boolean ret = true;
        try {
            insert(entity);
        } catch (Exception e) {
            log.info("e -> {}", e.getMessage());
            ret = false;
        }
        return ret;
    }

    public void start(Integer policyId) {
        CrawlUrl crawlUrl = getNewestUrl(policyId);
        if (null == crawlUrl) {
            return;
        }
        crawlUrlService.updateStatus(crawlUrl.getId(), StatusEnum.DOING.getCode());
        StatusEnum statusEnum = parseDetail(crawlUrl) ? StatusEnum.DONE : StatusEnum.FAIL;
        crawlUrlService.updateStatus(crawlUrl.getId(), statusEnum.getCode());
    }

}
